package controller

import (
	"fmt"
	"strconv"
	"uap/common"
	"uap/pkg/app"
	"uap/pkg/logger"
	"uap/utils"

	"github.com/gin-gonic/gin"
)

type OpenApi struct {
}

func NewOpenApi() *OpenApi {
	return &OpenApi{}
}

func (a *OpenApi) GetAppById(c *gin.Context) {
	appId := c.DefaultQuery("appId", "")
	var tbApp TbApp
	common.Db.Table("tb_app").Where("app_id = ?", appId).First(&tbApp)
	// bytes, err := json.Marshal(tbApp)
	// if err != nil {
	// 	fmt.Println(err)
	// }
	// re := base64.StdEncoding.EncodeToString(bytes)
	app.Success(c, tbApp)
}

func (a *OpenApi) GetUserInfo(c *gin.Context) {
	code := c.DefaultQuery("code", "")
	appId := c.DefaultQuery("appId", "")
	sign := c.DefaultQuery("sign", "")
	if code == "" || appId == "" || sign == "" {
		app.Error(c, 300, "")
		return
	}
	var tbApp TbApp
	common.Db.Table("tb_app").Where("app_id=?", appId).First(&tbApp)
	if tbApp.AppSecret == "" {
		app.Error(c, 300, "")
		return
	}
	if sign != utils.MD5Str(appId+tbApp.AppSecret) {
		app.Error(c, 300, "")
		return
	}
	userId, ok := common.CodeCache.Get(code)
	if ok {
		fmt.Println(userId)
	}
	var tbuser TbUser
	common.Db.Table("tb_user").Where("id=?", userId).First(&tbuser)
	if tbuser.Username == "" {
		app.Error(c, 300, "")
		return
	}
	tbuser.Password = ""
	app.Success(c, tbuser)
}

func (a *OpenApi) Login(ctx *gin.Context) {
	var loginRequest LoginRequest
	err := ctx.ShouldBind(&loginRequest)
	if err != nil {
		fmt.Println(err)
	}

	var tbuser TbUser
	common.Db.Table("tb_user").Where("username = ?", loginRequest.Username).First(&tbuser)
	if tbuser.Password == "" {
		app.Error(ctx, app.UserNoExist.Code, app.UserNoExist.Msg)
		return
	}
	if tbuser.Password == loginRequest.Password {
		user := utils.User{Username: tbuser.Username, Nickname: tbuser.Nickname, Id: strconv.Itoa(tbuser.Id)}
		logger.Infof("login user:%v", user)
		token, err3 := utils.GenToken(user)
		if err3 != nil {
			fmt.Println("生成token异常", err3)
		}
		app.Success(ctx, token)
		return
	} else {
		app.Error(ctx, app.UserOrPasswordError.Code, app.UserOrPasswordError.Msg)
		return
	}
}

func (a *OpenApi) CreateRobot(c *gin.Context) {
	appId := c.DefaultQuery("appId", "")
	sign := c.DefaultQuery("sign", "")
	if appId == "" || sign == "" {
		app.Error(c, 300, "")
		return
	}

	app.Success(c, "")
}
